package com.ruoyi.fatigue.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.fatigue.domain.vo.StartDetectionForm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口调用工具服务接口
 *
 * @author wasd11203
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class HttpUtilService {

    @Value("${redis-keys.detection-prefix}")
    private String isDetection;

    @Value("${link.base}")
    private String baseUrl;
    @Value("${link.infrared-camera.open}")
    private String infraredCameraOpen;
    @Value("${link.infrared-camera.close}")
    private String infraredCameraClose;
    @Value("${link.binocular-camera.open}")
    private String binocularCameraOpen;
    @Value("${link.binocular-camera.close}")
    private String binocularCameraClose;

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 开始检测
     * @param form
     */
    public void startDetection(StartDetectionForm form){
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前未登陆");
        }
        Long userId = loginUser.getUserId();
        if (userId == null) {
            throw new ServiceException("当前未登陆");
        }
        String userIdStr = String.valueOf(userId);

        List<String> range = stringRedisTemplate.opsForList().range(isDetection, 0, -1);
        if (range == null || range.isEmpty()) {
            range = new ArrayList<>();
        }
        if (range.contains(userIdStr)) {
            throw new ServiceException("不要多次开启红外相机或者双目摄像头");
        }
        try {
            String infraredUrl = baseUrl+infraredCameraOpen;
            JSONObject infraredReq = new JSONObject();
            infraredReq.putOpt("exe_path", form.getInfraredExePath());
            infraredReq.putOpt("timefolder", form.getInfraredTimeFolder());
            String infraredResp = HttpUtil.createPost(infraredUrl).body(JSONUtil.toJsonStr(infraredReq)).execute().body();
            log.info("开启红外相机请求结果：{}",infraredResp);
            JSONObject infraredJson = JSONUtil.parseObj(infraredResp);
            if (!"001".equals(infraredJson.getStr("status_code"))){
                throw new ServiceException("开启红外相机失败");
            }

            String binocularUrl = baseUrl+binocularCameraOpen;
            JSONObject binocularReq = new JSONObject();
            binocularReq.putOpt("image_path", form.getBinocularImgPath());
            String binocularResp = HttpUtil.createPost(binocularUrl).body(JSONUtil.toJsonStr(binocularReq)).execute().body();
            log.info("开启双目摄像头请求结果：{}",binocularResp);
            JSONObject binocularJson = JSONUtil.parseObj(infraredResp);
            if (!"001".equals(binocularJson.getStr("status_code"))){
                throw new ServiceException("开启双目摄像头失败");
            }
            range.add(userIdStr);
        }catch (Exception e){
            range.remove(userIdStr);
            throw new ServiceException(e.getMessage());
        }finally {
            stringRedisTemplate.delete(isDetection);
            if (CollUtil.isNotEmpty(range)){
                stringRedisTemplate.opsForList().leftPushAll(isDetection,range);
            }
        }
    }

    /**
     * 停止检测
     */
    public void stopDetection(){
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前未登陆");
        }
        Long userId = loginUser.getUserId();
        if (userId == null) {
            throw new ServiceException("当前未登陆");
        }
        String userIdStr = String.valueOf(userId);

        List<String> range = stringRedisTemplate.opsForList().range(isDetection, 0, -1);
        if (range == null || range.isEmpty()) {
            range = new ArrayList<>();
        }
        if (!range.contains(userIdStr)) {
            throw new ServiceException("不要多次关闭红外相机或者双目摄像头");
        }
        try {
            String infraredUrl = baseUrl+infraredCameraClose;
            JSONObject infraredReq = new JSONObject();
            String infraredResp = HttpUtil.createPost(infraredUrl).body(JSONUtil.toJsonStr(infraredReq)).execute().body();
            log.info("关闭红外相机请求结果：{}",infraredResp);
            JSONObject infraredJson = JSONUtil.parseObj(infraredResp);
            if (!"001".equals(infraredJson.getStr("status_code"))){
                throw new ServiceException("关闭红外相机失败");
            }

            String binocularUrl = baseUrl+binocularCameraClose;
            JSONObject binocularReq = new JSONObject();
            String binocularResp = HttpUtil.createPost(binocularUrl).body(JSONUtil.toJsonStr(binocularReq)).execute().body();
            log.info("关闭双目摄像头请求结果：{}",binocularResp);
            JSONObject binocularJson = JSONUtil.parseObj(infraredResp);
            if (!"001".equals(binocularJson.getStr("status_code"))){
                throw new ServiceException("关闭双目摄像头失败");
            }
            range.remove(userIdStr);
        }catch (Exception e){
            range.add(userId.toString());
            range = range.stream().distinct().collect(Collectors.toList());
            throw new ServiceException(e.getMessage());
        }finally {
            stringRedisTemplate.delete(isDetection);
            if (CollUtil.isNotEmpty(range)){
                stringRedisTemplate.opsForList().leftPushAll(isDetection,range);
            }
        }


    }

}
